<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      go/2-Go语言基础/16-结构体 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>go/2-Go语言基础/16-结构体</h2>



  <p class="post-date">2019-02-09</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><hr>
<p>title: “16-结构体”<br>date: 2019-03-10 08:08<br>tags:</p>
<ul>
<li>Go</li>
</ul>
<hr>
<h3 id="什么是结构体？"><a href="#什么是结构体？" class="headerlink" title="什么是结构体？"></a>什么是结构体？</h3><p>结构体是用户定义的类型，表示若干个字段（Field）的集合。有时应该把数据整合在一起，而不是让这些数据没有联系。这种情况下可以使用结构体。</p>
<p>例如，一个职员有 <code>firstName</code>、<code>lastName</code> 和 <code>age</code> 三个属性，而把这些属性组合在一个结构体 <code>employee</code> 中就很合理。</p>
<h3 id="结构体的声明"><a href="#结构体的声明" class="headerlink" title="结构体的声明"></a>结构体的声明</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;</span><br><span class="line">    firstName <span class="keyword">string</span></span><br><span class="line">    lastName  <span class="keyword">string</span></span><br><span class="line">    age       <span class="keyword">int</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的代码片段里，声明了一个结构体类型 <code>Employee</code>，它有 <code>firstName</code>、<code>lastName</code> 和 <code>age</code> 三个字段。通过把相同类型的字段声明在同一行，结构体可以变得更加紧凑。在上面的结构体中，<code>firstName</code> 和 <code>lastName</code> 属于相同的 <code>string</code> 类型，于是这个结构体可以重写为：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;</span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age, salary         <span class="keyword">int</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的结构体 <code>Employee</code> 称为 <strong>命名的结构体（Named Structure）</strong>。我们创建了名为 <code>Employee</code> 的新类型，而它可以用于创建 <code>Employee</code> 类型的结构体变量。  </p>
<p>声明结构体时也可以不用声明一个新类型，这样的结构体类型称为 <strong>匿名结构体（Anonymous Structure）</strong>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> employee <span class="keyword">struct</span> &#123;</span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age <span class="keyword">int</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述代码片段创建一个<strong>匿名结构体</strong> <code>employee</code>。</p>
<h3 id="创建命名的结构体"><a href="#创建命名的结构体" class="headerlink" title="创建命名的结构体"></a>创建命名的结构体</h3><p>通过下面代码，我们定义了一个<strong>命名的结构体 Employee</strong>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age, salary         <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//creating structure using field names</span></span><br><span class="line">    emp1 := Employee&#123;</span><br><span class="line">        firstName: <span class="string">"Sam"</span>,</span><br><span class="line">        age:       <span class="number">25</span>,</span><br><span class="line">        salary:    <span class="number">500</span>,</span><br><span class="line">        lastName:  <span class="string">"Anderson"</span>,</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//creating structure without using field names</span></span><br><span class="line">    emp2 := Employee&#123;<span class="string">"Thomas"</span>, <span class="string">"Paul"</span>, <span class="number">29</span>, <span class="number">800</span>&#125;</span><br><span class="line"></span><br><span class="line">    fmt.Println(<span class="string">"Employee 1"</span>, emp1)</span><br><span class="line">    fmt.Println(<span class="string">"Employee 2"</span>, emp2)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上述程序的第 7 行，我们创建了一个命名的结构体 <code>Employee</code>。而在第 15 行，通过指定每个字段名的值，我们定义了结构体变量 <code>emp1</code>。字段名的顺序不一定要与声明结构体类型时的顺序相同。在这里，我们改变了 <code>lastName</code> 的位置，将其移到了末尾。这样做也不会有任何的问题。</p>
<p>在上面程序的第 23 行，定义 <code>emp2</code> 时我们省略了字段名。在这种情况下，就需要保证字段名的顺序与声明结构体时的顺序相同。</p>
<p>该程序将输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Employee 1 &#123;Sam Anderson 25 500&#125;</span><br><span class="line">Employee 2 &#123;Thomas Paul 29 800&#125;</span><br></pre></td></tr></table></figure>

<h3 id="创建匿名结构体"><a href="#创建匿名结构体" class="headerlink" title="创建匿名结构体"></a>创建匿名结构体</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    emp3 := <span class="keyword">struct</span> &#123;</span><br><span class="line">        firstName, lastName <span class="keyword">string</span></span><br><span class="line">        age, salary         <span class="keyword">int</span></span><br><span class="line">    &#125;&#123;</span><br><span class="line">        firstName: <span class="string">"Andreah"</span>,</span><br><span class="line">        lastName:  <span class="string">"Nikola"</span>,</span><br><span class="line">        age:       <span class="number">31</span>,</span><br><span class="line">        salary:    <span class="number">5000</span>,</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    fmt.Println(<span class="string">"Employee 3"</span>, emp3)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上述程序的第 3 行，我们定义了一个<strong>匿名结构体变量</strong> <code>emp3</code>。上面我们已经提到，之所以称这种结构体是匿名的，是因为它只是创建一个新的结构体变量 <code>em3</code>，而没有定义任何结构体类型。</p>
<p>该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Employee 3 &#123;Andreah Nikola 31 5000&#125;</span><br></pre></td></tr></table></figure>

<h3 id="结构体的零值（Zero-Value）"><a href="#结构体的零值（Zero-Value）" class="headerlink" title="结构体的零值（Zero Value）"></a>结构体的零值（Zero Value）</h3><p>当定义好的结构体并没有被显式地初始化时，该结构体的字段将默认赋为零值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age, salary         <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> emp4 Employee <span class="comment">//zero valued structure</span></span><br><span class="line">    fmt.Println(<span class="string">"Employee 4"</span>, emp4)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该程序定义了 <code>emp4</code>，却没有初始化任何值。因此 <code>firstName</code> 和 <code>lastName</code> 赋值为 string 的零值（<code>&quot;&quot;</code>）。而 <code>age</code> 和 <code>salary</code> 赋值为 int 的零值（0）。该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Employee 4 &#123; 0 0&#125;</span><br></pre></td></tr></table></figure>

<p>当然还可以为某些字段指定初始值，而忽略其他字段。这样，忽略的字段名会赋值为零值。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age, salary         <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    emp5 := Employee&#123;</span><br><span class="line">        firstName: <span class="string">"John"</span>,</span><br><span class="line">        lastName:  <span class="string">"Paul"</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Println(<span class="string">"Employee 5"</span>, emp5)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面程序中的第 14 行和第 15 行，我们初始化了 <code>firstName</code> 和 <code>lastName</code>，而 <code>age</code> 和 <code>salary</code> 没有进行初始化。因此 <code>age</code> 和 <code>salary</code> 赋值为零值。该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Employee 5 &#123;John Paul 0 0&#125;</span><br></pre></td></tr></table></figure>

<h3 id="访问结构体的字段"><a href="#访问结构体的字段" class="headerlink" title="访问结构体的字段"></a>访问结构体的字段</h3><p>点号操作符 <code>.</code> 用于访问结构体的字段。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age, salary         <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    emp6 := Employee&#123;<span class="string">"Sam"</span>, <span class="string">"Anderson"</span>, <span class="number">55</span>, <span class="number">6000</span>&#125;</span><br><span class="line">    fmt.Println(<span class="string">"First Name:"</span>, emp6.firstName)</span><br><span class="line">    fmt.Println(<span class="string">"Last Name:"</span>, emp6.lastName)</span><br><span class="line">    fmt.Println(<span class="string">"Age:"</span>, emp6.age)</span><br><span class="line">    fmt.Printf(<span class="string">"Salary: $%d"</span>, emp6.salary)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面程序中的 <strong>emp6.firstName</strong> 访问了结构体 <code>emp6</code> 的字段 <code>firstName</code>。该程序输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">First Name: Sam  </span><br><span class="line">Last Name: Anderson  </span><br><span class="line">Age: 55  </span><br><span class="line">Salary: $6000</span><br></pre></td></tr></table></figure>

<p>还可以创建零值的 <code>struct</code>，以后再给各个字段赋值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age, salary         <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> emp7 Employee</span><br><span class="line">    emp7.firstName = <span class="string">"Jack"</span></span><br><span class="line">    emp7.lastName = <span class="string">"Adams"</span></span><br><span class="line">    fmt.Println(<span class="string">"Employee 7:"</span>, emp7)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面程序中，我们定义了 <code>emp7</code>，接着给 <code>firstName</code> 和 <code>lastName</code> 赋值。该程序会输出：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Employee 7: &#123;Jack Adams 0 0&#125;</span><br></pre></td></tr></table></figure>

<h3 id="结构体的指针"><a href="#结构体的指针" class="headerlink" title="结构体的指针"></a>结构体的指针</h3><p>还可以创建指向结构体的指针。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age, salary         <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    emp8 := &amp;Employee&#123;<span class="string">"Sam"</span>, <span class="string">"Anderson"</span>, <span class="number">55</span>, <span class="number">6000</span>&#125;</span><br><span class="line">    fmt.Println(<span class="string">"First Name:"</span>, (*emp8).firstName)</span><br><span class="line">    fmt.Println(<span class="string">"Age:"</span>, (*emp8).age)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面程序中，<strong>emp8</strong> 是一个指向结构体 <code>Employee</code> 的指针。<code>(*emp8).firstName</code> 表示访问结构体 <code>emp8</code> 的 <code>firstName</code> 字段。该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">First Name: Sam</span><br><span class="line">Age: 55</span><br></pre></td></tr></table></figure>

<p><strong>Go 语言允许我们在访问 firstName 字段时，可以使用 emp8.firstName 来代替显式的解引用 (*emp8).firstName</strong>。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName, lastName <span class="keyword">string</span></span><br><span class="line">    age, salary         <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    emp8 := &amp;Employee&#123;<span class="string">"Sam"</span>, <span class="string">"Anderson"</span>, <span class="number">55</span>, <span class="number">6000</span>&#125;</span><br><span class="line">    fmt.Println(<span class="string">"First Name:"</span>, emp8.firstName)</span><br><span class="line">    fmt.Println(<span class="string">"Age:"</span>, emp8.age)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的程序中，我们使用 <code>emp8.firstName</code> 来访问 <code>firstName</code> 字段，该程序会输出：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">First Name: Sam</span><br><span class="line">Age: 55</span><br></pre></td></tr></table></figure>

<h3 id="匿名字段"><a href="#匿名字段" class="headerlink" title="匿名字段"></a>匿名字段</h3><p>当我们创建结构体时，字段可以只有类型，而没有字段名。这样的字段称为匿名字段（Anonymous Field）。  </p>
<p>以下代码创建一个 <code>Person</code> 结构体，它含有两个匿名字段 <code>string</code> 和 <code>int</code>。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;  </span><br><span class="line">    <span class="keyword">string</span></span><br><span class="line">    <span class="keyword">int</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们接下来使用匿名字段来编写一个程序。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;  </span><br><span class="line">    <span class="keyword">string</span></span><br><span class="line">    <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    p := Person&#123;<span class="string">"Naveen"</span>, <span class="number">50</span>&#125;</span><br><span class="line">    fmt.Println(p)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的程序中，结构体 <code>Person</code> 有两个匿名字段。<code>p := Person{&quot;Naveen&quot;, 50}</code> 定义了一个 <code>Person</code> 类型的变量。该程序输出 <code>{Naveen 50}</code>。  </p>
<p><strong>虽然匿名字段没有名称，但其实匿名字段的名称就默认为它的类型</strong>。比如在上面的 <code>Person</code> 结构体里，虽说字段是匿名的，但 Go 默认这些字段名是它们各自的类型。所以 <code>Person</code> 结构体有两个名为 <code>string</code> 和 <code>int</code> 的字段。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;  </span><br><span class="line">    <span class="keyword">string</span></span><br><span class="line">    <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> p1 Person</span><br><span class="line">    p1.<span class="keyword">string</span> = <span class="string">"naveen"</span></span><br><span class="line">    p1.<span class="keyword">int</span> = <span class="number">50</span></span><br><span class="line">    fmt.Println(p1)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面程序的第 14 行和第 15 行，我们访问了 <code>Person</code> 结构体的匿名字段，我们把字段类型作为字段名，分别为 “string” 和 “int”。上面程序的输出如下：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;naveen 50&#125;</span><br></pre></td></tr></table></figure>

<h3 id="嵌套结构体（Nested-Structs）"><a href="#嵌套结构体（Nested-Structs）" class="headerlink" title="嵌套结构体（Nested Structs）"></a>嵌套结构体（Nested Structs）</h3><p>结构体的字段有可能也是一个结构体。这样的结构体称为嵌套结构体。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Address <span class="keyword">struct</span> &#123;  </span><br><span class="line">    city, state <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;  </span><br><span class="line">    name <span class="keyword">string</span></span><br><span class="line">    age <span class="keyword">int</span></span><br><span class="line">    address Address</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> p Person</span><br><span class="line">    p.name = <span class="string">"Naveen"</span></span><br><span class="line">    p.age = <span class="number">50</span></span><br><span class="line">    p.address = Address &#123;</span><br><span class="line">        city: <span class="string">"Chicago"</span>,</span><br><span class="line">        state: <span class="string">"Illinois"</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Println(<span class="string">"Name:"</span>, p.name)</span><br><span class="line">    fmt.Println(<span class="string">"Age:"</span>,p.age)</span><br><span class="line">    fmt.Println(<span class="string">"City:"</span>,p.address.city)</span><br><span class="line">    fmt.Println(<span class="string">"State:"</span>,p.address.state)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的结构体 <code>Person</code> 有一个字段 <code>address</code>，而 <code>address</code> 也是结构体。该程序输出：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Name: Naveen  </span><br><span class="line">Age: 50  </span><br><span class="line">City: Chicago  </span><br><span class="line">State: Illinois</span><br></pre></td></tr></table></figure>

<h3 id="提升字段（Promoted-Fields）"><a href="#提升字段（Promoted-Fields）" class="headerlink" title="提升字段（Promoted Fields）"></a>提升字段（Promoted Fields）</h3><p>如果是结构体中有匿名的结构体类型字段，则该匿名结构体里的字段就称为提升字段。这是因为提升字段就像是属于外部结构体一样，可以用外部结构体直接访问。我知道这种定义很复杂，所以我们直接研究下代码来理解吧。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Address <span class="keyword">struct</span> &#123;  </span><br><span class="line">    city, state <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;  </span><br><span class="line">    name <span class="keyword">string</span></span><br><span class="line">    age  <span class="keyword">int</span></span><br><span class="line">    Address</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的代码片段中，<code>Person</code> 结构体有一个匿名字段 <code>Address</code>，而 <code>Address</code> 是一个结构体。现在结构体 <code>Address</code> 有 <code>city</code> 和 <code>state</code> 两个字段，访问这两个字段就像在 <code>Person</code> 里直接声明的一样，因此我们称之为提升字段。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Address <span class="keyword">struct</span> &#123;</span><br><span class="line">    city, state <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;</span><br><span class="line">    name <span class="keyword">string</span></span><br><span class="line">    age  <span class="keyword">int</span></span><br><span class="line">    Address</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> p Person</span><br><span class="line">    p.name = <span class="string">"Naveen"</span></span><br><span class="line">    p.age = <span class="number">50</span></span><br><span class="line">    p.Address = Address&#123;</span><br><span class="line">        city:  <span class="string">"Chicago"</span>,</span><br><span class="line">        state: <span class="string">"Illinois"</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Println(<span class="string">"Name:"</span>, p.name)</span><br><span class="line">    fmt.Println(<span class="string">"Age:"</span>, p.age)</span><br><span class="line">    fmt.Println(<span class="string">"City:"</span>, p.city) <span class="comment">//city is promoted field</span></span><br><span class="line">    fmt.Println(<span class="string">"State:"</span>, p.state) <span class="comment">//state is promoted field</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面代码中的第 26 行和第 27 行，我们使用了语法 <code>p.city</code> 和 <code>p.state</code>，访问提升字段 <code>city</code> 和 <code>state</code> 就像它们是在结构体 <code>p</code> 中声明的一样。该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Name: Naveen  </span><br><span class="line">Age: 50  </span><br><span class="line">City: Chicago  </span><br><span class="line">State: Illinois</span><br></pre></td></tr></table></figure>

<h3 id="导出结构体和字段"><a href="#导出结构体和字段" class="headerlink" title="导出结构体和字段"></a>导出结构体和字段</h3><p>如果结构体名称以大写字母开头，则它是其他包可以访问的导出类型（Exported Type）。同样，如果结构体里的字段首字母大写，它也能被其他包访问到。  </p>
<p>让我们使用自定义包，编写一个程序来更好地去理解它。  </p>
<p>在你的 Go 工作区的 <code>src</code> 目录中，创建一个名为 <code>structs</code> 的文件夹。另外在 <code>structs</code> 中再创建一个目录 <code>computer</code>。  </p>
<p>在 <code>computer</code> 目录中，在名为 <code>spec.go</code> 的文件中保存下面的程序。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> computer</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Spec <span class="keyword">struct</span> &#123; <span class="comment">//exported struct  </span></span><br><span class="line">    Maker <span class="keyword">string</span> <span class="comment">//exported field</span></span><br><span class="line">    model <span class="keyword">string</span> <span class="comment">//unexported field</span></span><br><span class="line">    Price <span class="keyword">int</span> <span class="comment">//exported field</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的代码片段中，创建了一个 <code>computer</code> 包，里面有一个导出结构体类型 <code>Spec</code>。<code>Spec</code> 有两个导出字段 <code>Maker</code> 和 <code>Price</code>，和一个未导出的字段 <code>model</code>。接下来我们会在 main 包中导入这个包，并使用 <code>Spec</code> 结构体。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"structs/computer"</span>  </span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> spec computer.Spec</span><br><span class="line">    spec.Maker = <span class="string">"apple"</span></span><br><span class="line">    spec.Price = <span class="number">50000</span></span><br><span class="line">    fmt.Println(<span class="string">"Spec:"</span>, spec)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>包结构如下所示：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">src  </span><br><span class="line">   structs</span><br><span class="line">        computer</span><br><span class="line">            spec.go</span><br><span class="line">        main.go</span><br></pre></td></tr></table></figure>

<p>在上述程序的第 3 行，我们导入了 <code>computer</code> 包。在第 8 行和第 9 行，我们访问了结构体 <code>Spec</code> 的两个导出字段 <code>Maker</code> 和 <code>Price</code>。执行命令 <code>go install structs</code> 和 <code>workspacepath/bin/structs</code>，运行该程序。  </p>
<p>如果我们试图访问未导出的字段 <code>model</code>，编译器会报错。将 <code>main.go</code> 的内容替换为下面的代码。  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"structs/computer"</span>  </span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> spec computer.Spec</span><br><span class="line">    spec.Maker = <span class="string">"apple"</span></span><br><span class="line">    spec.Price = <span class="number">50000</span></span><br><span class="line">    spec.model = <span class="string">"Mac Mini"</span></span><br><span class="line">    fmt.Println(<span class="string">"Spec:"</span>, spec)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面程序的第 10 行，我们试图访问未导出的字段 <code>model</code>。如果运行这个程序，编译器会产生错误：<strong>spec.model undefined (cannot refer to unexported field or method model)</strong>。  </p>
<h3 id="结构体相等性（Structs-Equality）"><a href="#结构体相等性（Structs-Equality）" class="headerlink" title="结构体相等性（Structs Equality）"></a>结构体相等性（Structs Equality）</h3><p><strong>结构体是值类型。如果它的每一个字段都是可比较的，则该结构体也是可比较的。如果两个结构体变量的对应字段相等，则这两个变量也是相等的</strong>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> name <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName <span class="keyword">string</span></span><br><span class="line">    lastName <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    name1 := name&#123;<span class="string">"Steve"</span>, <span class="string">"Jobs"</span>&#125;</span><br><span class="line">    name2 := name&#123;<span class="string">"Steve"</span>, <span class="string">"Jobs"</span>&#125;</span><br><span class="line">    <span class="keyword">if</span> name1 == name2 &#123;</span><br><span class="line">        fmt.Println(<span class="string">"name1 and name2 are equal"</span>)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">"name1 and name2 are not equal"</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    name3 := name&#123;firstName:<span class="string">"Steve"</span>, lastName:<span class="string">"Jobs"</span>&#125;</span><br><span class="line">    name4 := name&#123;&#125;</span><br><span class="line">    name4.firstName = <span class="string">"Steve"</span></span><br><span class="line">    <span class="keyword">if</span> name3 == name4 &#123;</span><br><span class="line">        fmt.Println(<span class="string">"name3 and name4 are equal"</span>)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">"name3 and name4 are not equal"</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的代码中，结构体类型 <code>name</code> 包含两个 <code>string</code> 类型。由于字符串是可比较的，因此可以比较两个 <code>name</code> 类型的结构体变量。  </p>
<p>上面代码中 <code>name1</code> 和 <code>name2</code> 相等，而 <code>name3</code> 和 <code>name4</code> 不相等。该程序会输出：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">name1 and name2 are equal  </span><br><span class="line">name3 and name4 are not equal</span><br></pre></td></tr></table></figure>

<p><strong>如果结构体包含不可比较的字段，则结构体变量也不可比较。</strong>  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> image <span class="keyword">struct</span> &#123;  </span><br><span class="line">    data <span class="keyword">map</span>[<span class="keyword">int</span>]<span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    image1 := image&#123;data: <span class="keyword">map</span>[<span class="keyword">int</span>]<span class="keyword">int</span>&#123;</span><br><span class="line">        <span class="number">0</span>: <span class="number">155</span>,</span><br><span class="line">    &#125;&#125;</span><br><span class="line">    image2 := image&#123;data: <span class="keyword">map</span>[<span class="keyword">int</span>]<span class="keyword">int</span>&#123;</span><br><span class="line">        <span class="number">0</span>: <span class="number">155</span>,</span><br><span class="line">    &#125;&#125;</span><br><span class="line">    <span class="keyword">if</span> image1 == image2 &#123;</span><br><span class="line">        fmt.Println(<span class="string">"image1 and image2 are equal"</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面代码中，结构体类型 <code>image</code> 包含一个 <code>map</code> 类型的字段。由于 <code>map</code> 类型是不可比较的，因此 <code>image1</code> 和 <code>image2</code> 也不可比较。如果运行该程序，编译器会报错：<strong>main.go:18: invalid operation: image1 == image2 (struct containing map[int]int cannot be compared)</strong>。  </p>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
    
      <a class="nav-right" href="/go/2-Go%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/18-%E6%8E%A5%E5%8F%A3%EF%BC%88%E4%B8%80%EF%BC%89/">
        
          go/2-Go语言基础/18-接口（一）
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#什么是结构体？"><span class="toc-nav-text">什么是结构体？</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#结构体的声明"><span class="toc-nav-text">结构体的声明</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#创建命名的结构体"><span class="toc-nav-text">创建命名的结构体</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#创建匿名结构体"><span class="toc-nav-text">创建匿名结构体</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#结构体的零值（Zero-Value）"><span class="toc-nav-text">结构体的零值（Zero Value）</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#访问结构体的字段"><span class="toc-nav-text">访问结构体的字段</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#结构体的指针"><span class="toc-nav-text">结构体的指针</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#匿名字段"><span class="toc-nav-text">匿名字段</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#嵌套结构体（Nested-Structs）"><span class="toc-nav-text">嵌套结构体（Nested Structs）</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#提升字段（Promoted-Fields）"><span class="toc-nav-text">提升字段（Promoted Fields）</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#导出结构体和字段"><span class="toc-nav-text">导出结构体和字段</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#结构体相等性（Structs-Equality）"><span class="toc-nav-text">结构体相等性（Structs Equality）</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/go/2-Go语言基础/16-结构体/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "go/2-Go语言基础/16-结构体",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>